package com.yggdrasil.graphics;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.util.TreeSet;

import com.yggdrasil.graphics.input.KeyHandler;
import com.yggdrasil.world.Enemy;
import com.yggdrasil.world.NPC;

/**
 * WorldView is the window where you see your character in the world.
 *
 */
public class WorldView extends Canvas {

	private static final long serialVersionUID = 1L;
	// Offset based on player position
	volatile int xOffset, yOffset;
	public static final int WIDTH = 1280, HEIGHT = 600;
	Tile[] world;
	private TreeSet<Drawable> draw = new TreeSet<Drawable>();
	

	public WorldView(Tile[] world, KeyHandler kh) {
		setSize(WIDTH, HEIGHT);
		setPreferredSize(new Dimension(1280, 600));
		setBackground(Color.black);
		addKeyListener(kh);
		this.world = world;
	}
	
	/**
	 * Add a Drawable to this object.
	 * @param d Drawable to add.
	 */
	public void addDrawable(Drawable d) {
		System.out.println(draw.add(d));
		System.out.println(d);
		for (Drawable b : draw) 
			System.out.println(b);
	}

	public void display() {
		BufferStrategy bs = getBufferStrategy();
		if (bs == null) {
			createBufferStrategy(3);
			return;
		}
		Graphics g = bs.getDrawGraphics();

		// Clear screen
		g.setColor(Color.black);
		g.fillRect(0, 0, WIDTH, HEIGHT);

		/*
		int xOffset = (int) p.getX() - getWidth() / 2;
		if (xOffset < 0)
			xOffset = 0;
		int yOffset = (int) p.getY() - getHeight() / 2;
		if (yOffset < 0)
			yOffset = 0;
		*/

		for (int y = 0; y <= HEIGHT / Tile.HEIGHT + 1; y++) {
			for (int x = 0; x <= WIDTH / Tile.WIDTH + 1; x++) {
				g.drawImage(world[x + (xOffset / Tile.WIDTH)
						+ (y * x + (yOffset / Tile.HEIGHT))].type.img, x
						* Tile.WIDTH - xOffset % Tile.WIDTH, y * Tile.HEIGHT
						- yOffset % Tile.HEIGHT, Tile.WIDTH, Tile.HEIGHT, null);

			}
		}

		for (Drawable d : draw) {
			if (d instanceof NPC) {
				g.setColor(Color.blue);
				g.fillRect((int) d.getX() - xOffset, (int) d.getY() - yOffset, 30, 30);
			} else if (d instanceof Enemy) {
				g.setColor(Color.red);
				g.fillOval((int) d.getX() - xOffset, (int) d.getY() - yOffset, 40, 40);
			} else {
				g.setColor(Color.black);
				g.fillOval((int) d.getX(), (int) d.getY(), 32, 32);
			}
		}
		
		/*
		for (NPC n : npcs) {
			f.fillRect((int) n.getX() - xOffset, (int) n.getY() - yOffset, 30,
					30);
			n.randomMovement();
		}
		for (Enemy en : enemies) {
			if (en.isAlive()) {
				e.fillOval((int) en.getX() - xOffset,
						(int) en.getY() - yOffset, 50, 50);
				en.randomMovement();
				if(en.inHitbox((int)p.getX(), (int)p.getY())){
					System.out.println("In hitbox: " + en);
				}
			}
		}
		System.out.println("x: " + p.getX() + " y: " + p.getY());
		*/
		g.dispose();
		bs.show();
	}
}
